package com.kurancy.web.controller;

import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kurancy.domain.Faq;
import com.kurancy.domain.KurancyUser;
import com.kurancy.domain.enums.KurancyStatus;
import com.kurancy.domain.exception.InvalidTokenException;
import com.kurancy.domain.exception.NotFoundException;
import com.kurancy.service.kurancycreated.KurancySearchService;
import com.kurancy.web.authentication.service.AuthService;
import com.kurancy.web.controller.form.KurancyCreatedSearchForm;
import com.kurancy.web.controller.form.KurancyPaypalSearchForm;

@RequestMapping("/")
@Controller
public class HomePageController {

    @Autowired
	private KurancySearchService kurancySearchService;
    
    @Autowired
    private AuthService authService;

	/** The logger. */
	private static Log logger = LogFactory.getLog(HomePageController.class);

	@RequestMapping(method = RequestMethod.POST)
    public String searchForToken(@Valid KurancyCreatedSearchForm searchForm, BindingResult bindingResult, ModelMap map, Model uiModel, HttpServletRequest httpServletRequest) {
		
		logger.debug("Started:");
		if (bindingResult.hasErrors()) {
			createSearchForm(map, searchForm);
            return "homepage/index";
        }
    	String token = searchForm.getKurancyToken();
    	String compositeToken = "";
    	if (token.indexOf("-") == 4) {
    		compositeToken = token.substring(0, 4) + token.substring(5);
    	}
    	   	
    	try {
    		KurancyStatus status = kurancySearchService.validateToken(compositeToken);
	    	
    		if (status.equals(KurancyStatus.ACTIVE)) {
	    		return currencyFound(map, compositeToken);
	    	} else  {
	    		createSearchForm(map, searchForm);
	    		bindingResult.rejectValue("kurancyToken", "kurancy.token." + status.getValue());
	    		return "homepage/index";
	    	}
    	} catch (NotFoundException e) {
    		createSearchForm(map, searchForm);
    		bindingResult.rejectValue("kurancyToken", "kurancy.token.not.found");
    		return "homepage/index";
    	} catch (InvalidTokenException e) {
    		createSearchForm(map, searchForm);
    		bindingResult.rejectValue("kurancyToken", "kurancy.token.invalid");
    		return "homepage/index";
    	}
    }

    private String currencyFound(ModelMap map, String compositeToken) {
    	map.addAttribute("kurancyToken", compositeToken);
    	
    	KurancyUser kurancyUser = authService.getKurancyUser();
    	if (kurancyUser.getPaypalCredential() ==null || kurancyUser.getPaypalCredential().length() < 1 ) {
    		KurancyPaypalSearchForm form = new KurancyPaypalSearchForm();
    		form.setKurancyToken(compositeToken);
    		map.addAttribute("kurancyPaypalSearchForm", form);
    		return "claim/getPaypalInfo";
    	}
		return "claimKurancy";
	}

	@RequestMapping
    public String index( ModelMap map) {
    	
    	createSearchForm(map, null);
    	
        return "index";
    }

	private void createSearchForm(ModelMap map, KurancyCreatedSearchForm existingForm) {
		KurancyCreatedSearchForm form = null;
		if (existingForm == null) {
			form = new KurancyCreatedSearchForm();
    		map.addAttribute("searchForm", form);
		} else { 
			map.addAttribute("searchForm", existingForm);
		}
	}
	
	@RequestMapping("/faq")
	private String getFaq(ModelMap map) {
		
		TypedQuery<Faq> query = Faq.findActiveFaqsGroupByGroupNameOrderBySortOrder();
		if (query != null && !query.getResultList().isEmpty()) {
			map.addAttribute("faqs", query.getResultList());
		}
		return "faq";
	}
}
